import { Cascader } from 'antd'
import { isEmpty } from 'lodash-es'
import { useEffect, useState } from 'react'
import { forwardRef } from 'react'

import { requestWithTry } from '@/utils/request'

/**
 * @typedef {Object} OtherProps
 * @property {Promise} [api] 接口
 * @property {Object} [params] 额外参数
 * @property {funciton} [contentRender] 处理返回值
 * @property {funciton} [afterLoad] 数据请求完成
 */

/**
 * @typedef {import("antd/es/cascader").CascaderProps & OtherProps} AekCascaderProps
 */

/**
 * 级联选择
 * @param {AekCascaderProps} props
 * @returns
 */
const AekCascader = (props, ref) => {
  const { api, fieldNames = {}, params = {}, contentRender = _ => _, afterLoad, value, ...otherProps } = props
  const {
    value: fieldNamesValue = 'id',
    label: fieldNamesLabel = 'name',
    children: fieldNamesChildren = 'children',
  } = fieldNames

  const [loading, setLoading] = useState(false)
  const [dataSource, setDataSource] = useState([])

  const getData = async () => {
    if (!api) return
    setLoading(true)
    const { data } = await requestWithTry(api, params).finally(() => {
      setLoading(false)
    })

    const tree = contentRender(data.content || data || [])
    setDataSource(tree)
    afterLoad && afterLoad(tree)
  }

  useEffect(() => {
    getData()
  }, [JSON.stringify(params)])

  return (
    <Cascader
      {...{
        ref,
        loading,
        allowClear: true,
        showSearch: true,
        placeholder: '请选择',
        options: dataSource,
        fieldNames: { value: fieldNamesValue, label: fieldNamesLabel, children: fieldNamesChildren },
        ...otherProps,
        value: isEmpty(dataSource) && isEmpty(otherProps.treeData) ? undefined : value,
      }}
    />
  )
}

export default forwardRef(AekCascader)
